<script setup>
import { ref, watch } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { get, post } from "@/request/request";
import { config } from "@/config";
import TnRadio from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio.vue'
import TnRadioGroup from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio-group.vue'
import TnIcon from '@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue'
import TnDateTimePicker from '@tuniao/tnui-vue3-uniapp/components/date-time-picker/src/date-time-picker.vue'
import TnPicker from '@tuniao/tnui-vue3-uniapp/components/picker/src/picker.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'

const username = ref('');
const openDateTimePicker = ref(false);
const dateTimeValue = ref('');

const openPicker = ref(false);
const pickerValue = ref('');
const chooseImag = ref(false);
const reginName = ref('请选择地区');

const userForm = ref({
  avatars: '',
  avatarImg: '',
  nickname: '',
  province: 0,
  city: 0,
  county: 0,
  intro: '',
  sex: 0,
  sexName: '未知',
  birthday: '',
})
const pickerData = ref([]);
const textarea = ref('');

const genders = ref([{
  label: '男',
  value: 1,
}, {
  label: '女',
  value: 2,
}, {
  label: '未知',
  value: 0,
}])

onLoad(() => {
  get('/public_api/get_regin').then(res => {
    const reg = convertData(res.data);
    pickerData.value = reg;
  })
})

onShow(() => {
  get('/user_my').then(res => {
    const { data } = res;
    updateUserFormData(data);
  })
})

const updateUserFormData = (data) => {
  userForm.value.nickname = data.nickname;
  userForm.value.avatarImg = data.avatar;
  userForm.value.birthday = data.birthday;
  userForm.value.sex = data.sex;
  const sex = genders.value.find(item => item.value == data.sex);
  userForm.value.sexName = sex.label;
  const newcity = [data.province, data.city, data.county];
  pickerValue.value = newcity;
  userForm.value.province = data.province;
  userForm.value.city = data.city;
  userForm.value.county = data.county;
  userForm.value.intro = data.intro;
  reginName.value = data.provinceName ? `${data.provinceName}, ${data.cityName}, ${data.countyName}` : '请选择地区';
}

const handleInput = (e) => {
  username.value = e.target.value;
};

const genderClick = (e) => {
  const sex = genders.value.find(item => item.label == e);
  userForm.value.sex = sex.value;
  userForm.value.sexName = e;
}

const timeClick = () => {
  openDateTimePicker.value = true;
}

const confirmClick = (e) => {
  const convertedDate = convertDateFormat(e);
  userForm.value.birthday = convertedDate;
}

const convertDateFormat = (dateString) => {
  return dateString.replace(/\//g, '-');
}

const regionClick = () => {
  openPicker.value = true;
}

const confirmPocker = (e) => {
  userForm.value.province = e[0];
  userForm.value.city = e[1];
  userForm.value.county = e[2]
  const result = getNameByIds(e);
  reginName.value = result;
}

const textareaClick = (e) => {
  userForm.value.intro = e.detail.value;
}

const onChooseAvatar = (e) => {
  userForm.value.avatars = e.detail.avatarUrl;
  chooseImag.value = true;
}

const subClick = (e) => {
  post('/user_edit', userForm.value, {
    "Content-Type": "application/x-www-form-urlencoded",
    "sessionKey": uni.getStorageSync("sessionKey")
  }).then(res => {
    if (res.code == 200) {
      uni.showToast({
        title: '修改成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        }
      });
    }
    console.log('edit:', res.code)
  })
}

const getNameByIds = (ids) => {
  const names = [];
  let currentLevel = pickerData.value;
  for (let id of ids) {
    const item = currentLevel.find(item => item.value === id);
    if (item) {
      names.push(item.label);
      currentLevel = item.children;
    } else {
      break;
    }
  }
  return names.join(', ');
}

const convertData = (arr) => {
  return arr.map(item => {
    const children = item.children.length ? convertData(item.children) : null;
    const data = {
      label: item.name,
      value: item.id,
    };
    if (children) {
      data.children = children;
    }
    return data;
  });
}

// watch(userForm, (newValue, oldValue) => {
//   // 在此处可以添加表单数据变化时的逻辑处理
// });

</script>


<template>
  <view class="app">
    <view class="avatar_box">
      <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar_btn">
        <image class="avatar_img"
          :src="chooseImag ? userForm.avatars : (userForm.avatarImg ? config.baseUrl + '/file/' + userForm.avatarImg : userForm.avatars)" />
      </button>
    </view>


    <view class="title_t">
      <view style="font-size: 32rpx">用户名</view>
      <input @change="handleInput" v-model="userForm.nickname" style="width: 80%;height: 100%" type="nickname"
        placeholder="请输入用户名">
    </view>
    <view class="line" />
    <view class="title_t">
      <view style="font-size: 32rpx">性别</view>
      <TnRadioGroup v-model="userForm.sexName" active-color="#0d57d6" @change="genderClick">
        <template v-for="item in genders">
          <TnRadio :label="item.label">{{ item.label }}</TnRadio>
        </template>
      </TnRadioGroup>
    </view>
    <view class="line" />
    <view class="title_t" @click="timeClick">
      <view style="font-size: 32rpx">生日</view>
      <view style="display: flex;align-items: center;justify-content: space-around" @click="timeClick">
        <view style="font-size: 32rpx;color: #a6a6a6">{{ userForm.birthday }}</view>
        <TnIcon name="right" size="32" color="#a6a6a6" />
      </view>
    </view>
    <view class="line" />
    <view class="title_t">
      <view style="font-size: 32rpx">地区</view>
      <view style="display: flex;align-items: center;justify-content: space-around" @click="regionClick">
        <view style="font-size: 32rpx;color: #a6a6a6">{{ reginName }}</view>
        <TnIcon name="right" size="32" color="#a6a6a6" />
      </view>
    </view>
    <view class="line" />
    <view class="Curriculum">
      <view style="font-size: 32rpx;margin-top: -160rpx;">个人简历</view>
      <textarea class="c_input" v-model="userForm.intro" placeholder="个人简历" placeholder-class="textarea-placeholder"
        @input="textareaClick" />
    </view>
    <view class="line" />
    <view class="sub_btn">
      <TnButton type="primary" width="686" height="96" bg-color="#0052D9" text-color="#fff" @click="subClick">保存
      </TnButton>

    </view>
  </view>
  <TnDateTimePicker v-model="dateTimeValue" v-model:open="openDateTimePicker" min-time="1950/01/01"
    @confirm="confirmClick" confirm-color="#0052D9" />
  <TnPicker v-model="pickerValue" v-model:open="openPicker" :data="pickerData" @confirm="confirmPocker"
    confirm-color="#0052D9" />
</template>

<style scoped lang="scss">
.app {
  padding: 15rpx;

  .avatar_box {
    width: 100%;
    height: 272rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    .avatar_btn {
      margin: 20rpx;
      border-radius: 9999rpx;
      width: 128rpx;
      height: 128rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0;
      overflow: hidden;


      .avatar_img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 999rpx;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .title_t {
    height: 102rpx;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .line {
    width: 100%;
    height: 3rpx;
    background: #E7E7E7;
  }

  .Curriculum {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    .c_input {
      margin: 20rpx;
      width: 76%;
      height: 200rpx;
    }
  }

  .sub_btn {
    position: fixed;
    bottom: 180rpx;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
